package com.yc.javaee.tomcat.impl;

import com.yc.javaee.Tomcat服务器;
import com.yc.javaee.tomcat.Cookie;
import com.yc.javaee.tomcat.HttpServletRequest;
import com.yc.javaee.tomcat.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class HttpServletResponseImpl implements HttpServletResponse {
    private HttpServletRequest request;
    private OutputStream out;
    private int status; // 结果码
    private String msg;    // 结果码描述
    // 头域参数集合
    private Map<String, String> headers = new LinkedHashMap<>();


    public HttpServletResponseImpl(Socket socket, HttpServletRequest request) throws IOException {
        out = socket.getOutputStream();
        this.request = request;
    }

    @Override
    public void flushBuffer() {
        String requestURI = request.getRequestURI();
        String filepath = Tomcat服务器.WEBROOT + requestURI;
        File file = new File(filepath);
        try {
            out.write(String.format("HTTP/1.1 %s %s\n",status, msg).getBytes());
            // 输出响应头域参数
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                out.write(String.format("%s: %s\n",entry.getKey(), entry.getValue()).getBytes());
            }
            // 输出cookie字段
            for (Cookie cookie : cookies) {
                out.write(String.format("%s: %s\n", "Set-Cookie", cookie).getBytes());
            }
            // CRLF 空行, 隔开头域与实体
            out.write("\n".getBytes());
            // 实体 BODY
            if (file.exists()) {
                // 静态资源实体
                FileInputStream fis = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int count;
                while ((count = fis.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
            } else {
                // 动态资源实体
                String body = caw.toString();
                if(body.isEmpty() == false){
                    // 输出内容
                    out.write(body.getBytes());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    CharArrayWriter caw = new CharArrayWriter(); // 字符数组流, 可以将数据写入内存缓存区
    PrintWriter writer = new PrintWriter(caw);  // 处理流, 需要构建时传入另一个流
    @Override
    public PrintWriter getWriter() {
        return writer;
    }

    @Override
    public OutputStream getOutputStream() {
        return null;
    }

    @Override
    public void setContentType(String type) {
        // 告诉浏览器返回的内容类型
        setHeader("Content-Type", type);
    }

    @Override
    public void setStatus(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    @Override
    public void setHeader(String name, String value) {
        this.headers.put(name, value);
    }

    @Override
    public void sendRedirect(String location) {
        setStatus(302,"Redirect");
        setHeader("Location", location);
    }

    private List<Cookie> cookies = new ArrayList<>();
    @Override
    public void addCookie(Cookie cookie) {
        cookies.add(cookie);
    }
}
